package com.tangsm.spring.mvc.mybatis.handler;

import com.tangsm.spring.mvc.mybatis.domain.dto.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * @author tangsm
 * @date 2021-08-19 09:35:56
 */
@RestControllerAdvice
public class MethodArgumentNotValidExceptionHandler {
    /**
     * validator 参数验证异常
     * @param ex 验证失败时抛出的异常
     * @return 返回异常信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();

        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError error : bindingResult.getFieldErrors()) {
            String field = error.getField();
            Object value = error.getRejectedValue();
            String msg = error.getDefaultMessage();
            String message = String.format("错误字段：%s，错误值：%s，原因：%s；", field, value, msg);
            stringBuilder.append(message).append("\r\n");
        }
        return new Result<>(false, stringBuilder.toString());
    }
}
